package com.focusai.efairy.ui.activity.location;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.focusai.efairy.R;
import com.focusai.efairy.business.location.AMapLocationManager;
import com.focusai.efairy.model.location.Location;
import com.focusai.efairy.ui.adapter.SelectLocationAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.ActivityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/9/7.
 */

public class AMapSearchLocationActivity extends SwipeBackBaseActivity implements View.OnClickListener, PoiSearch.OnPoiSearchListener {
    private final static int POI_SEARCH_COUNT = 20, POI_SEARCH_BOUND = 500;
    private RecyclerView mRecyclerView;
    private ImageView searchClearIcon;
    private TextView tv_no_location;
    private EditText txtSearchedit;

    private PoiSearch poiSearch;
    private PoiSearch.Query query;
    private List<Location> locationList;
    private SelectLocationAdapter mAdapter;
    private String keyWord = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_search_location);
        initView();
        setDefaultValues();
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    @Override
    protected void initView() {
        searchClearIcon = findView(R.id.search_header_clear);
        mRecyclerView = findView(R.id.search_location_lv);
        tv_no_location = findView(R.id.tv_no_location);
        txtSearchedit = findView(R.id.txtSearchedit);
        findView(R.id.searchBtn).setOnClickListener(this);
        findView(R.id.back_btn).setOnClickListener(this);
        searchClearIcon.setOnClickListener(this);
        txtSearchedit.setFocusable(true);
    }

    @Override
    protected void setDefaultValues() {
        locationList = new ArrayList<>();
        mAdapter = new SelectLocationAdapter(getContext());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.refreshData(locationList);
        txtSearchedit.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                startQuery();
                return true;
            }
        });
        txtSearchedit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyword = txtSearchedit.getText().toString();
                if (keyword == null || keyword.length() <= 0) {
                    searchClearIcon.setVisibility(View.GONE);
                } else {
                    searchClearIcon.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mAdapter.setListener(new SelectLocationAdapter.OnItemLayoutClickListener() {
            @Override
            public void onItemClick(Location location, int position) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(AMapSelectLocationActivity.KEY_SELECT_LOCATION_ITEM, location);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    private void startQuery() {
        keyWord = txtSearchedit.getText().toString();
        if (TextUtils.isEmpty(keyWord)) {
            showToast("请输入地址");
            return;
        }
        doSearchQuery(keyWord);
        ActivityUtils.hideInputManager(getContext());

    }

    protected void doSearchQuery(String keyWord) {
        query = new PoiSearch.Query(keyWord, "", "");
        query.setPageSize(POI_SEARCH_COUNT);
        query.setPageNum(0);
        query.setCityLimit(false);
        query.setDistanceSort(false);
        poiSearch = new PoiSearch(getContext(), query);
        poiSearch.setOnPoiSearchListener(this);
//        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(kdLocation.getmLatitude(), kdLocation.getmLongitude()), POI_SEARCH_BOUND, true));
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchBtn:
                startQuery();
                break;
            case R.id.search_header_clear:
                txtSearchedit.setText("");
                break;
            case R.id.back_btn:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int state) {
        if (state != 0 && poiResult != null && poiResult.getPois() != null) {
            List<PoiItem> list = poiResult.getPois();
            locationList.clear();
            for (PoiItem item : list) {
                locationList.add(AMapLocationManager.spoiItemToLocation(item));
            }
            showNoAddress(locationList.size() == 0);
            mAdapter.refreshData(locationList);
        }
    }

    private void showNoAddress(boolean noAddress) {
        if (noAddress) {
            tv_no_location.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            tv_no_location.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
